package websocket

import (
	"encoding/json"
	"iron_man_comm/src/common/log"
	"iron_man_comm/src/goroslib/pkg/msgs/std_msgs"
)

type IotWebsocketMessage struct {
	Cmd  string           `json:"cmd"`
	Data IotWebsocketData `json:"data"`
}

type IotWebsocketData struct {
	Topic string `json:"topic"`
	Data  string `json:"data"`
}

/**
{
    "cmd": "iot_cmd",
    "data": {
    	"topic": "/user/data/up", 	//topic name
    	"data": "xxxxx"				//iot消息内容
    }
}
*/
func (s *IotServer) processIOTData(message string) {
	var data IotWebsocketMessage
	err := json.Unmarshal([]byte(message), &data)
	if err != nil {
		log.Error("ws server process iot data fail, msg: %s", message)
		return
	}
	go s.publishIotCmdData(data.Data)
}

/**
 * @brief:  发布iot cmd数据
 * @author: haitao.lin
 */
func (s *IotServer) publishIotCmdData(data IotWebsocketData) {
	publisher, ok := s.publisherMap[data.Topic]
	if ok {
		log.Info("iot server publish topic: %s, data, %s", data.Topic, data.Data)
		msg := &std_msgs.String{Data: data.Data}
		publisher.Write(msg)
	} else {
		log.Error("iot server cannot find topic: %s, data: %s", data.Topic, data.Data)
	}
}
